package com.mingtu.guards.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.callback.StringDialogCallback;
import com.hjq.gson.factory.GsonFactory;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.PeopleExpandableAdapter;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.bean.MyDepartStaffBean;
import com.mingtu.guards.bean.MyDeptNameBean;
import com.mingtu.guards.entity.DataEntity;
import com.mingtu.guards.utils.MyConstant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;

public class SelectPeopleActivity extends MyBaseActivity {


    @BindView(R.id.listView)
    ExpandableListView expandableListView;
    @BindView(R.id.btn_select)
    Button btnSelect;
    @BindView(R.id.but_sure)
    Button butSure;
    private boolean selectAll;
    private List<DataEntity> dataEntityList = new ArrayList<>();
    private PeopleExpandableAdapter peopleExpandableAdapter;
    private List<MyDeptNameBean.DeptListBean> listBeans;
    private HashMap<String, Object> peopleInfo = new HashMap<>();

    private boolean isMultipleChoice = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_select_people;
    }

    @Override
    protected void initView() {
        setModuleTitle("选择人员");
        setTitleBarBackground(getResources().getDrawable(R.drawable.titlebar_line_bottom));
    }

    @Override
    protected void initData() {
        setOnClickEvent();
        getDeptData();
    }

    @Override
    protected void getData() {
        isMultipleChoice = getIntent().getBooleanExtra("isMultipleChoice", false);
    }

    @OnClick(R.id.but_sure)
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.but_sure:
                if (peopleInfo.size() != 0) {
                    //获取 userName 和 userId
                    List<HashMap<String, Object>> userHashMapList = new ArrayList<>();

                    Set<Map.Entry<String, Object>> en = peopleInfo.entrySet();
                    for (Map.Entry<String, Object> entry : en) {
                        HashMap<String, Object> userHashMap = (HashMap<String, Object>) entry.getValue(); //保存的是选中的用户名和id
                        userHashMapList.add(userHashMap);
                    }

                    HashMap<String, Object> selectedPeopleInfo = new HashMap<>();
                    selectedPeopleInfo.put("peopleInfoList", userHashMapList);

                    String infoStr = GsonUtils.toJson(selectedPeopleInfo);

                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putString("infoStr", infoStr);
                    intent.putExtras(bundle);
                    setResult(MyConstant.SELECT_PEOPLE_RESULTCODE, intent);

                    finish();
                } else {
                    ToastUtils.showLong("请选择人员！");
                }

                break;
        }
    }

    private void setOnClickEvent() {
        btnSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectAll = !selectAll;
                if (selectAll) {
                    //遍历设置全选
                    for (int i = 0; i < dataEntityList.size(); i++) {
                        for (int j = 0; j < dataEntityList.get(i).getChildrenDataList().size(); j++) {
                            dataEntityList.get(i).getChildrenDataList().get(j).setSelect(true);
                        }
                    }
                } else {
                    //遍历设置取消全选
                    for (int i = 0; i < dataEntityList.size(); i++) {
                        for (int j = 0; j < dataEntityList.get(i).getChildrenDataList().size(); j++) {
                            dataEntityList.get(i).getChildrenDataList().get(j).setSelect(false);
                        }
                    }
                }


                peopleExpandableAdapter.reFreshData(dataEntityList);
                btnSelect.setText(selectAll ? "取消全选" : "全选");
            }
        });
    }

    private void initAdapter() {
        peopleExpandableAdapter = new PeopleExpandableAdapter(this, dataEntityList);
        expandableListView.setAdapter(peopleExpandableAdapter);

        peopleExpandableAdapter.setCheckBoxListener(new PeopleExpandableAdapter.CheckBoxListener() {
            @Override
            public void checkStateListener(int groupPosition, int childPosition, boolean isChecked) {
                MyLogUtil.e(getClass().getSimpleName(), "isChecked:" + isChecked);
                if (isMultipleChoice) {
                    //状态初始化
                    for (int i = 0; i < dataEntityList.size(); i++) {
                        DataEntity dataEntity = dataEntityList.get(i);
                        List<DataEntity.ChildrenData> childrenDataList = dataEntity.getChildrenDataList();
                        if (childrenDataList != null) {
                            for (int j = 0; j < childrenDataList.size(); j++) {
                                DataEntity.ChildrenData childrenData = childrenDataList.get(j);
                                childrenData.setSelect(false);
                            }
                        }
                    }
                }


                List<DataEntity.ChildrenData> childrenDataList = dataEntityList.get(groupPosition).getChildrenDataList();
                DataEntity.ChildrenData childrenData = childrenDataList.get(childPosition);
                childrenData.setSelect(isChecked);

                String userName = childrenData.getSubContent();
                String mobile = childrenData.getMobile();
                int userId = childrenData.getId();

                peopleExpandableAdapter.reFreshData(dataEntityList);
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("name", userName); //此处命名为了和接口对应
                hashMap.put("userId", userId);
                hashMap.put("mobile", mobile);

                if (isMultipleChoice) {
                    if (isChecked) {
                        peopleInfo.put(groupPosition + "" + childPosition, hashMap);//false 的时候  添加
                    } else {
                        peopleInfo.remove(groupPosition + childPosition + ""); //false 的时候  删除
                    }
                } else {
                    //因为是单选，只放一条数据
                    peopleInfo.put("0", hashMap);
                }
            }
        });

        expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int groupPosition, long l) {
                DataEntity dataEntity = dataEntityList.get(groupPosition);
                List<DataEntity.ChildrenData> childrenDataList = dataEntity.getChildrenDataList(); //只有当子列表是空的时候才请求数据
                if (childrenDataList.size() == 0) {
                    int deptId = listBeans.get(groupPosition).getDeptId();
                    getDeptPeople(groupPosition, deptId);
                }
                return false;
            }
        });


    }

    /**
     * 获取部门
     */
    private void getDeptData() {
        OkGo.<String>post(MyConstant.POST_TASK_DEPT)
                .tag(this)
                .upJson("")
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            Gson gson = GsonFactory.getSingletonGson();
                            MyDeptNameBean mydeptNameBean = new MyDeptNameBean();
                            mydeptNameBean = gson.fromJson(result, MyDeptNameBean.class);
                            listBeans = mydeptNameBean.getDeptList();

                            if (listBeans != null) {
                                if (listBeans.size() > 0) {
                                    for (int i = 0; i < listBeans.size(); i++) {
//                                        List<DataEntity.ChildrenData> childrenData = new ArrayList<>();
//                                        for (int j = 0; j < 8; j++) {
//                                            DataEntity.ChildrenData children = new DataEntity.ChildrenData("学生" + (j + 1), false);
//                                            childrenData.add(children);
//                                        }
//                                        DataEntity dataEntity = new DataEntity((i + 1) + "班", childrenData);
//                                        dataEntityList.add(dataEntity);

                                        String deptName = listBeans.get(i).getName(); //保护站名字
                                        List<DataEntity.ChildrenData> childrenData = new ArrayList<>();
                                        DataEntity dataEntity = new DataEntity(deptName, childrenData);
                                        dataEntityList.add(dataEntity);

                                    }
                                    initAdapter();
                                }
                            }


                        }
                    }
                });
    }

    /**
     * 获取部门下的人员
     */
    private void getDeptPeople(int pPosition, int deptId) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("deptId", deptId);
        OkGo.<String>post(MyConstant.POST_TASK_DEPT_PERSON + "/" + deptId)
                .tag(this)
                .upJson("")
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                MyDepartStaffBean myDepartStaffBean = new MyDepartStaffBean();
                                myDepartStaffBean = gson.fromJson(result, MyDepartStaffBean.class);
                                List<MyDepartStaffBean.PersonListBean> personListBeans = myDepartStaffBean.getPersonList();

                                if (personListBeans != null) {
                                    if (personListBeans.size() > 0) {
                                        List<DataEntity.ChildrenData> childrenData = new ArrayList<>();
                                        for (int i = 0; i < personListBeans.size(); i++) {
                                            String staffName = personListBeans.get(i).getName(); //保护站下人员名字
                                            int userId = personListBeans.get(i).getUserId();
                                            String mobile = personListBeans.get(i).getMobile();
                                            DataEntity.ChildrenData children = new DataEntity.ChildrenData(staffName, false, userId, mobile);
                                            childrenData.add(children);

                                        }
                                        DataEntity dataEntity = dataEntityList.get(pPosition);
                                        dataEntity.setChildrenDataList(childrenData); //重新赋值

                                        peopleExpandableAdapter.reFreshData(dataEntityList);

                                        expandableListView.expandGroup(pPosition); //展开某个item
                                    } else {
                                        ToastUtils.showLong("抱歉，该机构下暂时没有工作人员哦~");
                                    }
                                } else {
                                    ToastUtils.showLong("抱歉，该机构下暂时没有工作人员哦~");
                                }
                            } catch (JsonSyntaxException e) {

                                ToastUtils.showLong(getResources().getString(com.mingtu.center.R.string.text_json_error));
                            }

                        }
                    }
                });

    }
}